<?php

namespace App\Models\Common;

use Carbon\Carbon;
use Illuminate\Database\Migrations\Migration;
use function now;

class BaseMigration extends Migration
{

    const TABLE_NAME = '';
    const DB_CONN = 'mysql_archives';
    const SPLIT_MODE = self::SPLIT_MODE_OPTION_MONTH;

    const SPLIT_MODE_OPTION_MONTH = 'M';
    const SPLIT_MODE_OPTION_YEAR = 'Y';

    public static function getTableName($datetime = null, string $splitMode = null): string
    {
        if (!$splitMode = $splitMode ?: static::SPLIT_MODE) {
            $splitMode = static::SPLIT_MODE_OPTION_MONTH;
        }

        try {
            if ($datetime) {
                $datetime = Carbon::parse($datetime);
            } else {
                $datetime = now();
            }
        } catch (\Throwable $exception) {
            $datetime = now();
        }

        switch (strtoupper($splitMode)) {
            case self::SPLIT_MODE_OPTION_MONTH:
                $suffix = '_' . $datetime->format('Y_m');
                break;
            case self::SPLIT_MODE_OPTION_YEAR:
            default:
                $suffix = '_' . $datetime->year;
                break;
        }
        return static::TABLE_NAME . $suffix;
    }
}
